package com.cmccgz.udacs_landlord_webapp.main.unlock;

import android.content.Intent;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.View;
import android.widget.DatePicker;
import android.widget.TextView;

import com.cmccgz.baselibrary.base.BaseActivity;
import com.cmccgz.baselibrary.view.ClearEditText;
import com.cmccgz.baselibrary.view.DatePickerDialog;
import com.cmccgz.baselibrary.view.MyDividerItemDecoration;
import com.cmccgz.udacs_landlord_webapp.R;
import com.cmccgz.udacs_landlord_webapp.adapter.UnlockRecordAdapter;
import com.cmccgz.udacs_landlord_webapp.bean.DeviceInfoBean;
import com.cmccgz.udacs_landlord_webapp.bean.UnlockRecord;
import com.cmccgz.udacs_landlord_webapp.main.device.view.SelectDevicesActivity;
import com.cmccgz.udacs_landlord_webapp.update.StringUtils;
import com.jcodecraeer.xrecyclerview.ProgressStyle;
import com.jcodecraeer.xrecyclerview.XRecyclerView;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created by June on 2017-6-19.
 */

public class UnlockRecordActivity extends BaseActivity implements UnlockRecordContract.View, XRecyclerView.LoadingListener, View.OnClickListener {

    private final static String TAG = UnlockRecordActivity.class.getSimpleName();
    private UnlockRecordContract.Presenter mPresenter;
    private TextView tv_title;
    private TextView tv_back;
    private ClearEditText et_search;
    private TextView btn_search;
    private XRecyclerView rv_list;
    private UnlockRecordAdapter adapter;
    private int page = 1;
    private TextView tv_start_date;
    private TextView tv_end_date;
    private TextView tv_device;
    private SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd");
    private final static int REQ_SEL_DEVICE=101;
    private DeviceInfoBean currentDevice=null;
    @Override
    protected int setLayoutId() {
        return R.layout.activity_unlock_record;
    }

    @Override
    protected void initView() {
        new UnlockRecordPresenter(this);
        tv_title = (TextView) findViewById(R.id.tv_title);
        tv_back = (TextView) findViewById(R.id.tv_back);
        tv_back.setVisibility(View.VISIBLE);
        et_search = (ClearEditText) findViewById(R.id.et_search);
        et_search.setHint("请输入房屋名称/租客姓名");
        btn_search = (TextView) findViewById(R.id.btn_search);
        rv_list = (XRecyclerView) findViewById(R.id.rv_list);
        tv_title.setText("进出记录");
        tv_start_date = ((TextView) findViewById(R.id.tv_start_date));
        tv_end_date = ((TextView) findViewById(R.id.tv_end_date));
        tv_device = ((TextView) findViewById(R.id.tv_device));
        initListener();
        initFiter();
        initRecyclerView();
        getRec(false,true);
    }

    private void initFiter() {
        long currentDate = new Date().getTime();
        tv_start_date.setText(formatDate(currentDate-6*24*60*60*1000));
        tv_end_date.setText(formatDate(currentDate));
    }

    private void initRecyclerView() {
        adapter = new UnlockRecordAdapter(mContext);
        LinearLayoutManager layoutManager = new LinearLayoutManager(mContext);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        rv_list.setLayoutManager(layoutManager);
        rv_list.setAdapter(adapter);
        rv_list.setRefreshProgressStyle(ProgressStyle.SysProgress);
        rv_list.setLoadingMoreProgressStyle(ProgressStyle.Pacman);
        rv_list.setLoadingListener(this);
        rv_list.addItemDecoration(new MyDividerItemDecoration(mContext, DividerItemDecoration.VERTICAL));
    }

    private void initListener() {
        tv_back.setOnClickListener(this);
        btn_search.setOnClickListener(this);
        tv_start_date.setOnClickListener(this);
        tv_end_date.setOnClickListener(this);
        tv_device.setOnClickListener(this);
    }

    @Override
    protected void initFragment() {

    }

    @Override
    protected void beforePermission() {

    }

    @Override
    protected int setSystemBarColorId() {
        return 0;
    }

    @Override
    public void setPresenter(UnlockRecordContract.Presenter presenter) {
        this.mPresenter = presenter;
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    private void getRec(boolean isLoadMore,boolean needsDialog) {
        if (isLoadMore) {
            page ++;
        }else{
            page = 1;
        }
        if (needsDialog) {
            showLoadingDialog("正在刷新数据");
        }
        mPresenter.loadRecord(et_search.getText().toString(),
                currentDevice==null|| StringUtils.isEmpty(currentDevice.device_id)?"":currentDevice.device_id,
                tv_start_date.getText().toString(),
                tv_end_date.getText().toString(), page);
    }

    @Override
    public void onRefresh() {
        getRec(false,false);
    }
    @Override
    public void onLoadMore() {
        getRec(true,false);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_back:
                onBackPressed();
                break;
            case R.id.btn_search:
                getRec(false,true);
                break;
            case R.id.tv_start_date:
                DatePickerDialog.showDateWithMaxAndCurrent(mContext, getText(R.string.starttime_dialong_title).toString(), parseDate(tv_end_date.getText().toString()), parseDate(tv_start_date.getText().toString()), new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                        String dateStr = year + "-" + (monthOfYear + 1) + "-" + dayOfMonth;
                        tv_start_date.setText(parseTrueDateStr(dateStr));
                        getRec(false,true);
                    }
                });
                break;
            case R.id.tv_end_date:
                DatePickerDialog.showDatePickerDialog(mContext, getText(R.string.endtime_dialong_title).toString(), parseDate(tv_start_date.getText().toString()), new Date().getTime(), parseDate(tv_end_date.getText().toString()), new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                        Log.e("INX", "onDateSet: "+year+"-"+monthOfYear+"-"+dayOfMonth);
                        String dateStr = year + "-" + (monthOfYear + 1) + "-" + dayOfMonth;
                        tv_end_date.setText(parseTrueDateStr(dateStr));
                        getRec(false,true);
                    }
                });
                break;
            case R.id.tv_device:
                Intent intent = new Intent(mContext, SelectDevicesActivity.class);
                intent.putExtra(SelectDevicesActivity.KEY_OPENALLSELECT,true);
                startActivityForResult(intent,REQ_SEL_DEVICE);
                break;
            default:
                break;
        }
    }

    @Override
    public void showLoading() {
        rv_list.setRefreshing(true);
    }

    @Override
    public void refreshSuccess(List<UnlockRecord> data) {
        rv_list.refreshComplete();
        adapter.changeData(data);
        dismissLoadingDialog();
    }

    @Override
    public void refreshFail(String errorMsg) {
        rv_list.refreshComplete();
        showToast(errorMsg);
        dismissLoadingDialog();
    }

    @Override
    public void loadmoreSuccess(List<UnlockRecord> data) {
        rv_list.loadMoreComplete();
        if (data.size() == 0) {
            page--;
        } else {
            adapter.appendData(data);
        }
        dismissLoadingDialog();
    }

    @Override
    public void loadmoreFail(String errorMsg) {
        rv_list.loadMoreComplete();
        page--;
        showToast(errorMsg);
        dismissLoadingDialog();
    }

    private long parseDate(String dateStr){
        long result=0;
        try {
            result=dateFormat.parse(dateStr).getTime();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
    private String parseTrueDateStr(String dateStr){
        long mil = parseDate(dateStr);
        return formatDate(mil);
    }
    private String formatDate(long dateMill){
        return dateFormat.format(dateMill);
    }
    private void asyDeviceView(){
        tv_device.setText(currentDevice==null?"所有设备":(StringUtils.isEmpty(currentDevice.device_name)?"未知设备":currentDevice.device_name));
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==REQ_SEL_DEVICE&&resultCode==RESULT_OK) {
            Serializable allSelect = data.getSerializableExtra(SelectDevicesActivity.KEY_IS_ALLSELECT);
            if (allSelect!=null) {
                currentDevice=null;
            }else{
                currentDevice= ((DeviceInfoBean) data.getSerializableExtra(SelectDevicesActivity.KEY_RESULT_DEVICE));
            }
            asyDeviceView();
            getRec(false,true);
        }
    }
}
